package com.his.system.manager.task;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 测试JDK Timer的执行
 *
 * @Description
 * @Author HHJ
 * @Date 2020-07-25 16:17
 */
public class MyTaskRunnableTest {
    private static final DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
    private static final DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");

    /**
     * 时间间隔(秒)
     */
    private static final long periodSecond = 60 * 1000;
    /**
     * 时间设置(已天为单位)
     */
    private static final String curStr = "11:00:00";

    public static void main(String[] args) {
        System.out.println("-----测试JDK Timer的执行-----开始");

        JdbcUserDao userDao = new JdbcUserDao();
        long initDelay = MyTaskRunnableTest.getTimeMillis(curStr);
        System.out.println("系统启动后下一次定时执行时间:" + initDelay / 1000 + "秒");
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
        executorService.scheduleAtFixedRate(
                new MyTaskRunnable("MyTaskRunnableTest", userDao),
                initDelay,
                periodSecond,
                TimeUnit.MILLISECONDS);

        System.out.println("-----测试JDK Timer的执行-----结束");
    }

    /**
     * 获取指定时间对应的毫秒数
     *
     * @param time “HH:mm:ss”
     * @return
     */
    private static long getTimeMillis(String time) {
        try {
            Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
            long initDelay = getInitDelay(curDate.getTime() - System.currentTimeMillis());
            return initDelay;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取下次执行时间
     *
     * @param initDelay
     * @return
     */
    private static long getInitDelay(long initDelay) {
        if (initDelay > 0) {
            return initDelay;
        }
        return getInitDelay(periodSecond + initDelay);
    }
}
